#pragma once

#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <thread>
#include <mutex>

int count2 = 100;
std::mutex mymutex2;

void *thread2(void *argv)
{
    while (1)
    {
        mymutex2.lock();
        if (count2 > 0)
        {
            usleep(1000);
            std::cout << "child thread tid: " << (char *)argv << " my count = " << count2 << std::endl;
            count2--;
            mymutex2.unlock();
        }
        else
        {
            mymutex2.unlock();
            return nullptr;
        }
    }
    return nullptr;
}

// cpp加锁
void cpp_mutex()
{
    std::thread pth1(thread2, (void *)"thread1");
    std::thread pth2(thread2, (void *)"thread2");
    std::thread pth3(thread2, (void *)"thread3");
    std::thread pth4(thread2, (void *)"thread4");
    std::thread pth5(thread2, (void *)"thread5");

    pth1.detach();
    pth2.detach();
    pth3.detach();
    pth4.detach();
    pth5.detach();

    while (count2 > 0)
    {
        usleep(1000);
    }
    usleep(2000);
}

